package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.bean.ReasonListBean
import com.gexiaobao.pigeon.app.model.param.AddOrReGoodsParam
import com.gexiaobao.pigeon.app.model.param.CancelOrderParam
import com.gexiaobao.pigeon.app.model.param.DelayShopReceiptParam
import com.gexiaobao.pigeon.app.model.param.RefundReturnParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentShopOrderListBinding
import com.gexiaobao.pigeon.ui.adapter.AllShopOrderListAdapter
import com.gexiaobao.pigeon.ui.adapter.HotGoodsAdapter
import com.gexiaobao.pigeon.ui.adapter.ReturnGoodsReasonAdapter
import com.gexiaobao.pigeon.ui.adapter.ShopOrderListAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.util.Date

/**
 * @Author      : hxw
 * @Date        : 2023/6/20 14:55
 * @Describe    : 我的订单列表
 */
class FragmentAllShopOrderList : BaseFragment<MallViewModel, FragmentShopOrderListBinding>() {

    private var viewHeader: View? = null
    private var swipeRecyclerViewHead: SwipeRecyclerView? = null
    private var index = -1
    private val mAdapter: AllShopOrderListAdapter by lazy { AllShopOrderListAdapter(arrayListOf()) }
    private val mAdapterNoPay: ShopOrderListAdapter by lazy { ShopOrderListAdapter(arrayListOf(), Date()) }
    private val mHotAdapter: HotGoodsAdapter by lazy { HotGoodsAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>
    private lateinit var dialog: RxDialogDefault
    private lateinit var dialogBottom: BottomSheetDialog//退款原因
    private lateinit var dialogCancelOrder: RxDialogDefault
    private val mAdapterReason: ReturnGoodsReasonAdapter by lazy { ReturnGoodsReasonAdapter(arrayListOf()) }
    private var mIsRefresh = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        index = requireArguments().getInt("index")

        /** 正在热卖 */
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mDatabind.swipeRecyclerViewHot.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.right = Util.dp2px(context, 5f)//右间距5dp
                outRect.left = Util.dp2px(context, 5f)//左间距5dp
                outRect.top = Util.dp2px(context, 5f)//上间距5dp
                outRect.bottom = Util.dp2px(context, 5f)//下间距5dp
            }
        })
        mDatabind.swipeRecyclerViewHot.layoutManager = layoutManager
        mDatabind.swipeRecyclerViewHot.adapter = mHotAdapter

        eventViewModel.toNoticeReceivedGoods.observeInFragment(this) {
            onRefresh(true)
        }
        eventViewModel.refundReturnResult.observeInFragment(this) {
            onRefresh(true)
        }
        eventViewModel.toNoticePaySuccess.observeInFragment(this) {
            onRefresh(true)
        }
        eventViewModel.toNoticeReturnGoods.observeInFragment(this) {
            onRefresh(true)
        }
        eventViewModel.toRefreshListShopOrder.observeInFragment(this) {
            onRefresh(true)
        }

        /** 初始化 swipeRecyclerView */
        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 10f)))
            it.initFooter {
                mIsRefresh = false
                mViewModel.getMyOrderShopList(mIsRefresh, index)
            }
        }

        mAdapterNoPay.setOnChildGoodsClickListener(object : ShopOrderListAdapter.OnChildItemClickListener {
            override fun onChildItemClick(position: Int) {
                nav().navigateAction(R.id.action_to_fragment_order_detail, Bundle().apply {
                    putString("orderId", mAdapterNoPay.data[position].id.toString())
                    putString("type", "list")
                })
            }
        })
        mAdapterNoPay.addChildClickViewIds(
            R.id.llList,
            R.id.tvItemToPay,
            R.id.tvItemDelOrder,
            R.id.shop_order_detail_status,
            R.id.shop_order_detail_status_more
        )
        mAdapterNoPay.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.shop_order_detail_status, R.id.shop_order_detail_status_more -> {
                    nav().navigateAction(R.id.action_to_fragment_merchant_store, Bundle().apply {
                        putInt("shopId", mAdapterNoPay.data[position].shopId)
                    })
                }

                R.id.llList, R.id.tvItemToPay -> {
                    nav().navigateAction(R.id.action_to_fragment_order_detail, Bundle().apply {
                        putString("orderId", mAdapterNoPay.data[position].id.toString())
                        putString("type", "list")
                    })
                }

                R.id.tvItemDelOrder -> {
                    cancelOrder(mAdapterNoPay.data[position].id)
                }
            }
        }

        /** 下拉刷新 */
        mDatabind.layoutList.swipeRefreshLayout.init {
            onRefresh(true)
        }

        /** 状态页配置 */
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            /** 点击重试时触发的操作 */
            onRefresh(true)
        }

        mHotAdapter.setOnItemClickListener { _, _, position ->
            nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                putString("id", mHotAdapter.data[position].goodsId.toString())
            })
        }

        mAdapter.setOnChildGoodsClickListener(object : AllShopOrderListAdapter.OnChildItemClickListener {
            override fun onChildItemClick(orderId: Int, orderStatus: Int) {
                when (orderStatus) {
                    0, 1 -> {
                        nav().navigateAction(R.id.action_to_fragment_order_detail, Bundle().apply {
                            putString("orderId", orderId.toString())
                            putString("type", "list")
                        })
                    }

                    2, 3 -> {//2-等待发货; 3-等待收货
                        nav().navigateAction(R.id.action_to_fragment_order_detail_progress, Bundle().apply {
                            putString("orderId", orderId.toString())
                        })
                    }

                    4, 9 -> {//4-已签收9-订单关闭
                        nav().navigateAction(R.id.action_to_fragment_order_detail_finish, Bundle().apply {
                            putString("orderId", orderId.toString())
                            putString("type", "1")//列表页跳入
                        })
                    }
                }

            }
        })

        mAdapter.addChildClickViewIds(
            R.id.tvItemButton1,
            R.id.tvItemButton2,
            R.id.tvItemButton3,
            R.id.tvItemButton4,
            R.id.tvItemButton5,
            R.id.llList,
            R.id.shop_order_detail_status,
            R.id.shop_order_detail_status_more
        )
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val orderStatus = mAdapter.data[position - 1].orderStatus
            when (view.id) {
                R.id.shop_order_detail_status, R.id.shop_order_detail_status_more -> {
                    nav().navigateAction(R.id.action_to_fragment_merchant_store, Bundle().apply {
                        putInt("shopId", mAdapter.data[position - 1].shopId)
                    })
                }

                R.id.tvItemButton1 -> {//删除订单
                    when (orderStatus) {
                        3 -> {
                            nav().navigateAction(R.id.action_to_fragment_logistics_progress, Bundle().apply {
                                putString("expressNo", mAdapter.data[position - 1].expressNo)
                                putInt("orderId", mAdapter.data[position - 1].orderId)
                            })
                        }

                        4, 7, 9, 12 -> {
                            delOrder(mAdapter.data[position - 1].orderId)
                        }
                    }
                }

                R.id.tvItemButton2 -> {
                    when (orderStatus) {
                        2 -> {//申请退款
                            showBottomDialogReason(position - 1)
                        }

                        3, 4 -> {//退换/售后
                            afterSales(position - 1)
                        }
                    }
                }

                R.id.tvItemButton3 -> {
                    when (orderStatus) {
                        2 -> {//修改订单
                            nav().navigateAction(R.id.action_to_fragment_modify_order, Bundle().apply {
                                putInt("orderId", mAdapter.data[position - 1].orderId)
                            })
                        }

                        3 -> {//确认收货
                            showReceivedGoodsDialog(mAdapter.data[position - 1].shopOrderId)
                        }

                        4, 7, 9, 10, 12 -> {//再次购买
                        }

                        5 -> {//重新支付

                        }

                        11, 13, 14 -> {//退货详情

                        }

                        15 -> {//我已寄出

                        }
                    }
                }

                R.id.tvItemButton4 -> {//再来一单
                    val body = DelayShopReceiptParam(mAdapter.data[position - 1].orderId)
                    mViewModel.moreOne(body)
                }

                R.id.tvItemButton5 -> {//延长收货
                    showExtendReceipt(mAdapter.data[position].orderId)
                }

                R.id.llList -> {
                    when (mAdapter.data[position - 1].orderStatus) {
                        2, 3 -> {
                            nav().navigateAction(R.id.action_to_fragment_order_detail_progress, Bundle().apply {
                                putString("orderId", mAdapter.data[position - 1].orderId.toString())
                            })
                        }

                        4, 9 -> {
                            nav().navigateAction(R.id.action_to_fragment_order_detail_finish, Bundle().apply {
                                putString("orderId", mAdapter.data[position - 1].orderId.toString())
                                putString("type", "1")//列表页跳入
                            })
                        }
                    }
                }
            }
        }

        mDatabind.swipeRecyclerViewNoPay.init(LinearLayoutManager(context), mAdapterNoPay).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 10f))
        )
        if (index == 0) {
            /** 添加头部布局，代付款的订单布局分开显示 */
            viewHeader = LayoutInflater.from(context).inflate(R.layout.all_order_list_header, null)
            swipeRecyclerViewHead = viewHeader?.findViewById(R.id.swipeRecyclerViewHead)
            swipeRecyclerViewHead?.init(LinearLayoutManager(context), mAdapterNoPay)?.addItemDecoration(
                SpaceItemDecoration(0, Util.dp2px(context, 10f))
            )
            val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            viewHeader?.layoutParams = layoutParams
            mDatabind.layoutList.swipeRecyclerView.addHeaderView(viewHeader)
        }
    }

    /** 延长收货 */
    private fun showExtendReceipt(orderId: Int) {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("确认延长收货时间")
        dialog.setContent("每笔订单只能延长一次哦")
        dialog.setCancelListener {
            dialog.dismiss()
        }
        dialog.setSureListener {
            val param = DelayShopReceiptParam(orderId)
            mViewModel.delayShopReceipt(param)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvShopOrderGo) {
            when (it) {
                mDatabind.tvShopOrderGo -> {
                    nav().navigateAction(R.id.action_to_fragment_mall_goods, Bundle().apply {
                        putInt("index", 0)
                    })
                }
            }
        }
    }

    private fun cancelOrder(id: Int) {
        dialogCancelOrder = RxDialogDefault(context)
        dialogCancelOrder.setTitle("是否取消该订单")
        dialogCancelOrder.setSureListener {
            val body = CancelOrderParam(orderId = id)
            showLoading(getString(R.string.loading))
            mViewModel.cancelOrder(body)
        }
        dialogCancelOrder.setFullScreenWidth()
        dialogCancelOrder.show()
    }

    private fun afterSales(position: Int) {
        var orderId = 0
        var goodId = ""
        if (!mAdapter.data[position].isEmpty()) {
            orderId = mAdapter.data[position].list[0].id
            goodId = mAdapter.data[position].list[0].goodId.toString()
        }
        nav().navigateAction(R.id.action_to_fragment_return_of_goods, Bundle().apply {
            putInt("orderId", orderId)
            putInt("shopUserId", mAdapter.data[position].shopId)
            putString("goodsId", goodId)
        })
    }

    /** 申请退换货 */
    private fun refundReturnGoods(position: Int, reason: String) {
        var goodsId = ""
        var mOrderId = 0
        var shopId = 0
        if (mAdapter.data.isNotEmpty() && !mAdapter.data[position].isEmpty()) {
            goodsId = mAdapter.data[position].list[0].goodId.toString()
            mOrderId = mAdapter.data[position].list[0].id
            shopId = mAdapter.data[position].shopId
        }
        showLoading(getString(R.string.loading))
        val body = RefundReturnParam(
            reason = reason,
            damage = 2,//1损坏2未损坏
            type = 1,
            goodsId = goodsId,
            orderId = mOrderId,
            shopUserId = shopId,
            reviewType = 1,//1-退款 2-退货 3-换货
        )
        mViewModel.addReturnReview(body)

    }

    private fun delOrder(id: Int) {
        dialog = RxDialogDefault(context)
        dialog.setTitle(getString(R.string.market_shop_order_sure_activity_sure_to_delete_order))
        dialog.setSureListener {
            showLoadingAntiShake(getString(R.string.loading))
            val body = AddOrReGoodsParam(id = id)
            mViewModel.userDeleteOrder(body)
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        onRefresh(true)
    }

    private fun onRefresh(isRefresh: Boolean) {
        mIsRefresh = true
        loadsir.showLoading()
        mViewModel.getMyOrderShopList(mIsRefresh, index)
        mViewModel.getMyOrderList(isRefresh, 1)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 再来一单 */
        mViewModel.moreOneResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                nav().navigateAction(R.id.action_to_fragment_shop_car)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取热卖商品列表 */
        mViewModel.HotGoodsListResult.observe(viewLifecycleOwner) {
            if (it.isEmpty()) {
                return@observe
            }
            mHotAdapter.setList(it.list)
            mHotAdapter.notifyDataSetChanged()
        }
        /** 确认收货 */
        mViewModel.confirmReceivedResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                RxToast.showToast("已确认收货")
                onRefresh(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 取消订单  */
        mViewModel.cancelOrderResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                dialogCancelOrder.dismiss()
                onRefresh(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取我的订单列表(待支付) */
        mViewModel.shopOrderListResult.observe(viewLifecycleOwner) {
            mAdapterNoPay.setList(it.listData)
            mAdapterNoPay.notifyDataSetChanged()
        }
        /** 申请退换货 */
        mViewModel.refundResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                dialogBottom.dismiss()
                RxToast.success("申请成功")
                onRefresh(true)
                eventViewModel.refundReturnResult.value = true
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 删除订单  */
        mViewModel.deleteOrderResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it.isSuccess) {
                dialog.dismiss()
                onRefresh(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取我的订单列表 */
        mViewModel.myShopOrderListResult.observe(viewLifecycleOwner) {
            if (it.isEmpty && mIsRefresh) {
                mDatabind.nestedScrollViewEmptyDataUI.visibility = View.VISIBLE
                mDatabind.layoutList.conList.visibility = View.GONE
                mViewModel.getHotSaleList()
            } else {
                mDatabind.nestedScrollViewEmptyDataUI.visibility = View.GONE
                mDatabind.layoutList.conList.visibility = View.VISIBLE
            }
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
    }

    /** 确认收货弹窗 */
    private fun showReceivedGoodsDialog(shopOrderId: Int) {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("是否确定收到货物？")
        dialog.setSureListener {
            showLoadingAntiShake(getString(R.string.loading))
            val body = AddOrReGoodsParam(id = shopOrderId)
            mViewModel.confirmShopReceipt(body)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    @SuppressLint("MissingInflatedId", "NotifyDataSetChanged")
    private fun showBottomDialogReason(position: Int) {
        val mList = ArrayList<ReasonListBean>()
        mList.add(ReasonListBean("7天无理由"))
        mList.add(ReasonListBean("商品与页面描述不符"))
        mList.add(ReasonListBean("少件/发错货/未收到货"))
        mList.add(ReasonListBean("价格变化"))
        mList.add(ReasonListBean("商品破损/包装问题"))
        mList.add(ReasonListBean("商品质量/故障"))

        dialogBottom = context?.let { BottomSheetDialog(it, R.style.BottomSheetDialog) }!!
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_return_goods_reason, null)
        val swipeRecyclerView = dialogView.findViewById<SwipeRecyclerView>(R.id.swipeRecyclerView)
        val tvReturnGoodReason = dialogView.findViewById<AppCompatTextView>(R.id.tvReturnGoodReason)
        val ivCloseBottomDialog = dialogView.findViewById<AppCompatImageView>(R.id.ivCloseBottomDialog)

        swipeRecyclerView.init(LinearLayoutManager(context), mAdapterReason)
        swipeRecyclerView.adapter = mAdapterReason
        mAdapterReason.setList(mList)
        mAdapterReason.notifyDataSetChanged()

        var reasonContent = ""//退款原因
        mAdapterReason.setOnItemCheckClickListener(object : ReturnGoodsReasonAdapter.OnItemCheckClickListener {
            override fun onItemClick(position: Int) {
                reasonContent = mAdapterReason.data[position].reason
            }
        })
        ivCloseBottomDialog.setOnClickListener {
            dialogBottom.dismiss()
        }

        tvReturnGoodReason.setOnClickListener {
            refundReturnGoods(position, reasonContent)
        }
        dialogBottom.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialogBottom.setContentView(dialogView)
        dialogBottom.show()
    }

    companion object {
        fun newInstance(i: Int): FragmentAllShopOrderList {
            val fragment = FragmentAllShopOrderList()
            val bundle = Bundle()
            bundle.putInt("index", i)
            fragment.arguments = bundle
            return fragment
        }
    }
}